import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_app/components/article_card.dart';
import 'package:flutter_app/components/max_video_card.dart';
import 'package:flutter_app/components/song_card.dart';
import 'package:flutter_app/model/article_model.dart';
import 'package:flutter_app/model/recommend_interf.dart';
import 'package:flutter_app/model/song_model.dart';
import 'package:flutter_app/model/user_model.dart';
import 'package:flutter_app/model/video_model.dart';
import 'package:flutter_app/services/article_service.dart';
import 'package:flutter_app/services/recommend_service.dart';
import 'package:flutter_app/services/user_service.dart';
import 'package:flutter_app/services/video_service.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';

class RecommendPage extends StatefulWidget {
  RecommendPage({Key key}) : super(key: key);

  @override
  RecommendPageState createState() => RecommendPageState();
}

class RecommendPageState extends State<RecommendPage>
    with AutomaticKeepAliveClientMixin {
  EasyRefreshController _controller;

  // 独立的滚动视图 防止tab切换时触发下拉刷新
  ScrollController _scrollController;
  List<RecommendInterface> _recommendList = [];
  int page = 1;
  int limit = 10;
  bool hasMore = true;
  bool loading = true;
  bool error = false;
  String errorMsg = '';

//  String userType = 'DQ_SINGER';
  String userType = '';

  @override
  void initState() {
    super.initState();
    _controller = EasyRefreshController();
    _scrollController = ScrollController();
    _getRecommend();
  }

  @override
  void dispose() {
    _controller.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  Future _getRecommend({bool push = false}) async {
    try {
      //获取数据
//      List<dynamic> result =
//          await RecommendService().getRecommends(page: page, limit: limit);
      List<dynamic> result;
      String data = await rootBundle.loadString("assets/data/recommend.json");
      print(data);
      result = jsonDecode(data);
      print(result);
      List<RecommendInterface> recommendList = result.map((item) {
        if (item['songEntity'] != null) {
          return SongItem.fromJson(item['songEntity']);
        } else if (item['articleEntity'] != null) {
          return ArticleItem.fromJson(item['articleEntity']);
        } else if (item['videoEntity'] != null) {
          return VideoItem.fromJson(item['videoEntity']);
        }
      }).toList();
      print(recommendList);
      setState(() {
        page++;
        if (push) {
          _recommendList = recommendList;
        } else {
          _recommendList.addAll(recommendList);
        }
      });
    } catch (e) {
      setState(() {
        error = true;
        errorMsg = e.toString();
      });
    } finally {
      setState(() {
        loading = false;
      });
    }
  }

  //上拉加载
  Future _onRefresh() async {
    if (error) {
      setState(() => error = false);
    }
    page = 1;
    await _getRecommend();
    _controller.resetLoadState();
  }

  //下拉刷新
  Future _onLoad() async {
    if (hasMore) {
      await _getRecommend(push: false);
    }
    _controller.finishLoad(noMore: !hasMore);
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return EasyRefresh(
      // 开启首次加载刷新
      firstRefresh: true,
      // 加载时的loading
      // 空视图、异常视图

      enableControlFinishRefresh: false,
      enableControlFinishLoad: true,
      controller: _controller,
      header: ClassicalHeader(),
      footer: ClassicalFooter(),
      onRefresh: _onRefresh,
      onLoad: _onLoad,
      child: ListView.builder(
          controller: _scrollController,
          itemCount: _recommendList.length,
          itemBuilder: (BuildContext context, int index) {
            RecommendInterface widgetItem = _recommendList[index];
            return getWidgeByInterface(widgetItem);
          }),
    );
  }

  Widget getWidgeByInterface(RecommendInterface widgetItem) {
    if (widgetItem is SongItem) {
      return _columnBox(SongCard(songItem: widgetItem));
    } else if (widgetItem is ArticleItem) {
      return _columnBox(ArticleCard(articleItem: widgetItem));
    } else if (widgetItem is VideoItem) {
      return _columnBox(MaxVideoCard(videoItem: widgetItem));
    } else {
      return SizedBox.shrink();
    }
  }

  Widget _columnBox(Widget card) {
    return Column(
      children: [
        SizedBox(height: 8),
        card,
      ],
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;

  ///
}
